<?php
	class Principal extends CI_Controller
	{
		function index()
		{
			session_start();
			if(isset($_SESSION["host"]))
			{
				redirect("principal/login");
			}
			else
			{
				$this->load->view("login");
			}
		}
		function login()
		{
			session_start();
			if(!isset($_SESSION["host"]))
			{
				$this->load->library("form_validation");
				$this->form_validation->set_rules("host","Host","required");
				$this->form_validation->set_rules("puerto","Puerto","required");
				if($this->form_validation->run())
				{
					$host=$this->input->post("host");
					$puerto=$this->input->post("puerto");
					$socket=fsockopen($host,(int)$puerto);
					if($socket)
					{
						fputs($socket,"0");
						$_SESSION["host"]=$host;
						$_SESSION["puerto"]=$puerto;
						$str=fgets($socket,1024);
						print_r($str);
						$_SESSION["id"]=(int)$str;
						
						if(isset($_SESSION["host"]))
						{
							$this->load->view("principal");
						}
						else
						{
						redirect("principal/login");
						}
					}
					else
					{
						redirect("principal/login");
					}
				}
				else
				{
					$this->load->view("errorf");
				}
			}
			else
			{
				$this->load->view("principal");
			}
		}
		function logout()
		{
			session_start();
			$socket=fsockopen($_SESSION["host"],(int)$_SESSION["puerto"]);
			fputs($socket,$_SESSION["id"]);
			time_nanosleep(0,500000000);
			fputs($socket,"exit");
			session_destroy();
			fclose($socket);
			redirect("principal");
			
		}
	}
	
?>
